package com.duff.pdf.reader.pdfreader;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.duff.pdf.reader.library.PdfReaderActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button bt_open1;
    private Button bt_open2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt_open1 = (Button) findViewById(R.id.bt_open1);
        bt_open2 = (Button) findViewById(R.id.bt_open2);
        bt_open1.setOnClickListener(this);
        bt_open2.setOnClickListener(this);

        checkPermission();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_open1:
                openPdfFromExternalStorage();
                break;

            case R.id.bt_open2:
                openPdfFromAssets();
                break;
        }
    }

    private void openPdfFromExternalStorage() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/wzdt.pdf";
        Uri uri = Uri.fromFile(new File(path));
        intent.setDataAndType(uri, "application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        startActivity(intent);
    }

    private void openPdfFromAssets() {
        Intent intent = new Intent(MainActivity.this, PdfReaderActivity.class);
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/wzdt.pdf";
        intent.putExtra("pdf_path", path);

        startActivity(intent);
    }

    private void checkPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 没有权限，需要申请
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {

        }
    }

}
